<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  InputNumber,
  message,
  Row,
  Select,
  SelectOption,
  Space,
  Statistic,
  Table,
  TabPane,
  Tabs,
  Tag,
} from 'ant-design-vue';

import { getCapabilityInstances } from '#/api/resource-center';

// 响应式数据
const loading = ref(false);
const activePerformanceTab = ref('response-time');
const instanceList = ref([]);

// 监控概览数据
const overview = reactive({
  totalInstances: 0,
  enabledInstances: 0,
  todayCalls: 0,
  avgResponseTime: 0,
});

// 告警配置
const alertConfig = reactive({
  responseTimeThreshold: 1000,
  errorRateThreshold: 5,
  notificationChannels: ['email'],
});

// 表格列定义
const instanceColumns = [
  {
    title: '实例名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '能力类型',
    dataIndex: 'capabilityId',
    key: 'capabilityId',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '性能指标',
    key: 'performance',
    width: 200,
  },
  {
    title: '调用统计',
    key: 'metrics',
    width: 150,
  },
  {
    title: '最后调用',
    key: 'lastCall',
    width: 150,
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right',
  },
];

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap = {
    enabled: 'green',
    disabled: 'orange',
    error: 'red',
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    enabled: '启用',
    disabled: '禁用',
    error: '错误',
  };
  return textMap[status] || status;
};

// 获取能力名称
const getCapabilityName = (capabilityId: string) => {
  const nameMap = {
    booking_capability: '预订能力',
    payment_capability: '支付能力',
    notification_capability: '通知能力',
    report_capability: '报表能力',
  };
  return nameMap[capabilityId] || capabilityId;
};

// 格式化时间
const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleString();
};

// 加载监控数据
const loadMonitoringData = async () => {
  loading.value = true;
  try {
    // 加载实例列表
    const result = await getCapabilityInstances();
    if (result.code === 200) {
      instanceList.value = result.data || [];

      // 计算概览数据
      overview.totalInstances = instanceList.value.length;
      overview.enabledInstances = instanceList.value.filter(
        (item: any) => item.status === 'enabled',
      ).length;

      // 计算今日调用和平均响应时间
      let totalCalls = 0;
      let totalResponseTime = 0;
      let responseTimeCount = 0;

      instanceList.value.forEach((instance: any) => {
        totalCalls += instance.metrics.totalCalls;
        if (instance.metrics.averageResponseTime) {
          totalResponseTime += instance.metrics.averageResponseTime;
          responseTimeCount++;
        }
      });

      overview.todayCalls = totalCalls;
      overview.avgResponseTime =
        responseTimeCount > 0
          ? Math.round(totalResponseTime / responseTimeCount)
          : 0;
      responseTimeCount0Math
        .roundtotalResponseTimeresponseTimeCountresponseTimeCount0Math
        .roundtotalResponseTimeresponseTimeCount;
    }
  } catch (error) {
    console.error('加载监控数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  loadMonitoringData();
  message.success('数据已刷新');
};

// 导出报告
const exportReport = () => {
  message.info('导出监控报告功能开发中...');
  // TODO: 实现报告导出功能TODOTODO
};

// 查看实例详情
const viewInstanceDetail = (record: any) => {
  message.info(`查看实例详情: ${record.name}`);
  // TODO: 实现实例详情查看TODOTODO
};

// 查看实例日志
const viewInstanceLogs = (record: any) => {
  message.info(`查看实例日志: ${record.name}`);
  // TODO: 实现日志查看TODOTODO
};

// 测试实例
const testInstance = (record: any) => {
  message.info(`测试实例: ${record.name}`);
  // TODO: 实现实例测试TODOTODO
};

// 保存告警配置
const saveAlertConfig = () => {
  message.success('告警配置已保存');
  // TODO: 实现告警配置保存TODOTODO
};

// 测试告警
const testAlert = () => {
  message.success('测试告警已发送');
  // TODO: 实现告警测试TODOTODO
};

// 初始化
onMounted(() => {
  loadMonitoringData();
});
</script>

<template>
  <div class="capability-monitoring">
    <div class="monitoring-header">
      <h2>能力监控</h2>
      <div class="header-actions">
        <Button type="primary" @click="refreshData">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新
        </Button>
        <Button @click="exportReport">
          <IconifyIcon icon="ant-design:export-outlined" />
          导出报告
        </Button>
      </div>
    </div>

    <!-- 监控概览 -->
    <div class="monitoring-overview">
      <Row :gutter="16">
        <Col :span="6">
          <Card>
            <Statistic
              title="总能力实例"
              :value="overview.totalInstances"
              :value-style="{ color: '#3f8600' }"
            >
              <template #prefix>
                <IconifyIcon icon="ant-design:appstore-outlined" />
              </template>
            </Statistic>
          </Card>
        </Col>
        <Col :span="6">
          <Card>
            <Statistic
              title="启用实例"
              :value="overview.enabledInstances"
              :value-style="{ color: '#3f8600' }"
            >
              <template #prefix>
                <IconifyIcon icon="ant-design:check-circle-outlined" />
              </template>
            </Statistic>
          </Card>
        </Col>
        <Col :span="6">
          <Card>
            <Statistic
              title="今日调用"
              :value="overview.todayCalls"
              :value-style="{ color: '#1890ff' }"
            >
              <template #prefix>
                <IconifyIcon icon="ant-design:phone-outlined" />
              </template>
            </Statistic>
          </Card>
        </Col>
        <Col :span="6">
          <Card>
            <Statistic
              title="平均响应时间"
              :value="overview.avgResponseTime"
              suffix="ms"
              :value-style="{ color: '#722ed1' }"
            >
              <template #prefix>
                <IconifyIcon icon="ant-design:clock-circle-outlined" />
              </template>
            </Statistic>
          </Card>
        </Col>
      </Row>
    </div>

    <!-- 性能监控 -->
    <div class="performance-monitoring">
      <Card title="性能监控" class="monitoring-card">
        <Tabs v-model:active-key="activePerformanceTab">
          <TabPane key="response-time" tab="响应时间">
            <div class="chart-container">
              <div class="chart-placeholder">
                <Icon
                  icon="ant-design:line-chart-outlined"
                  class="chart-icon"
                />
                <p>响应时间趋势图</p>
                <p class="chart-desc">显示各能力实例的响应时间变化趋势</p>
              </div>
            </div>
          </TabPane>
          <TabPane key="throughput" tab="吞吐量">
            <div class="chart-container">
              <div class="chart-placeholder">
                <IconifyIcon
                  icon="ant-design:bar-chart-outlined"
                  class="chart-icon"
                />
                <p>吞吐量统计图</p>
                <p class="chart-desc">显示各能力实例的调用次数和成功率</p>
              </div>
            </div>
          </TabPane>
          <TabPane key="error-rate" tab="错误率">
            <div class="chart-container">
              <div class="chart-placeholder">
                <Icon
                  icon="ant-design:exclamation-circle-outlined"
                  class="chart-icon"
                />
                <p>错误率监控图</p>
                <p class="chart-desc">显示各能力实例的错误率和异常情况</p>
              </div>
            </div>
          </TabPane>
        </Tabs>
      </Card>
    </div>

    <!-- 实例状态监控 -->
    <div class="instance-monitoring">
      <Card title="实例状态监控" class="monitoring-card">
        <Table
          :columns="instanceColumns"
          :data-source="instanceList"
          :loading="loading"
          :pagination="false"
          row-key="id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <Tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </Tag>
            </template>

            <template v-else-if="column.key === 'capabilityId'">
              <Tag color="blue">
                {{ getCapabilityName(record.capabilityId) }}
              </Tag>
            </template>

            <template v-else-if="column.key === 'performance'">
              <div class="performance-indicators">
                <div class="indicator">
                  <span class="label">响应时间:</span>
                  <span class="value">{{ record.state.performance.responseTime }}ms</span>
                </div>
                <div class="indicator">
                  <span class="label">成功率:</span>
                  <span class="value">{{ record.state.performance.successRate }}%</span>
                </div>
                <div class="indicator">
                  <span class="label">吞吐量:</span>
                  <span class="value">{{ record.state.performance.throughput }}/s</span>
                </div>
              </div>
            </template>

            <template v-else-if="column.key === 'metrics'">
              <div class="metrics-summary">
                <div class="metric-item">
                  <span class="metric-label">总调用:</span>
                  <span class="metric-value">{{
                    record.metrics.totalCalls
                  }}</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">成功:</span>
                  <span class="metric-value success">{{
                    record.metrics.successCalls
                  }}</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">失败:</span>
                  <span class="metric-value error">{{
                    record.metrics.failedCalls
                  }}</span>
                </div>
              </div>
            </template>

            <template v-else-if="column.key === 'lastCall'">
              <span v-if="record.metrics.lastCallTime">
                {{ formatTime(record.metrics.lastCallTime) }}
              </span>
              <span v-else class="no-data">无调用记录</span>
            </template>

            <template v-else-if="column.key === 'actions'">
              <Space>
                <Button
                  type="link"
                  size="small"
                  @click="viewInstanceDetail(record)"
                >
                  <IconifyIcon icon="ant-design:eye-outlined" />
                  详情
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="viewInstanceLogs(record)"
                >
                  <IconifyIcon icon="ant-design:file-text-outlined" />
                  日志
                </Button>
                <Button type="link" size="small" @click="testInstance(record)">
                  <IconifyIcon icon="ant-design:experiment-outlined" />
                  测试
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </Card>
    </div>

    <!-- 告警设置 -->
    <div class="alert-settings">
      <Card title="告警设置" class="monitoring-card">
        <div class="alert-config">
          <Form :model="alertConfig" layout="vertical">
            <Row :gutter="16">
              <Col :span="8">
                <FormItem label="响应时间阈值">
                  <InputNumber
                    v-model:value="alertConfig.responseTimeThreshold"
                    :min="0"
                    :max="10000"
                    style="width: 100%"
                  />
                  <span class="unit">ms</span>
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="错误率阈值">
                  <InputNumber
                    v-model:value="alertConfig.errorRateThreshold"
                    :min="0"
                    :max="100"
                    :precision="2"
                    style="width: 100%"
                  />
                  <span class="unit">%</span>
                </FormItem>
              </Col>
              <Col :span="8">
                <FormItem label="告警通知">
                  <Select
                    v-model:value="alertConfig.notificationChannels"
                    mode="multiple"
                  >
                    <SelectOption value="email">邮件</SelectOption>
                    <SelectOption value="sms">短信</SelectOption>
                    <SelectOption value="webhook">Webhook</SelectOption>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <div class="alert-actions">
              <Button type="primary" @click="saveAlertConfig">
                <IconifyIcon icon="ant-design:save-outlined" />
                保存配置
              </Button>
              <Button @click="testAlert">
                <IconifyIcon icon="ant-design:bell-outlined" />
                测试告警
              </Button>
            </div>
          </Form>
        </div>
      </Card>
    </div>
  </div>
</template>

<style lang="less" scoped>
.capability-monitoring {
  .monitoring-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      color: #262626;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .monitoring-overview {
    margin-bottom: 24px;
  }

  .monitoring-card {
    margin-bottom: 24px;

    .chart-container {
      height: 300px;
      display: flex;
      align-items: center;
      justify-content: center;

      .chart-placeholder {
        text-align: center;
        color: #8c8c8c;

        .chart-icon {
          font-size: 48px;
          margin-bottom: 16px;
          color: #d9d9d9;
        }

        p {
          margin: 8px 0;
        }

        .chart-desc {
          font-size: 12px;
          color: #bfbfbf;
        }
      }
    }
  }

  .performance-indicators {
    .indicator {
      display: flex;
      justify-content: space-between;
      margin-bottom: 4px;
      font-size: 12px;

      .label {
        color: #8c8c8c;
      }

      .value {
        font-weight: 500;
      }
    }
  }

  .metrics-summary {
    .metric-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 4px;
      font-size: 12px;

      .metric-label {
        color: #8c8c8c;
      }

      .metric-value {
        font-weight: 500;

        &.success {
          color: #52c41a;
        }

        &.error {
          color: #ff4d4f;
        }
      }
    }
  }

  .no-data {
    color: #bfbfbf;
    font-style: italic;
  }

  .alert-config {
    .unit {
      margin-left: 8px;
      color: #8c8c8c;
    }

    .alert-actions {
      margin-top: 16px;
      display: flex;
      gap: 8px;
    }
  }
}
</style>
